package br.com.fiap.trabalho.dao;

import java.util.Calendar;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.fiap.trabalho.entity.Actor;
import br.com.fiap.trabalho.entity.Movie;

public class JPAActorDAO extends JPADAO<Actor> implements ActorDAO {

	public JPAActorDAO(EntityManager em) {
		super(em);
	}

	public Actor createActor(Actor actor) {
		return persist(actor);
	}

	public boolean deleteActor(Actor actor) {
		return delete(actor);
	}

	@SuppressWarnings("unchecked")
	public List<Actor> selectActorByName(String name) {
		Query query = em.createQuery("SELECT a FROM Actor a "
				+ "WHERE a.fullName = :actorName ");

		query.setParameter("actorName", name);
		return query.getResultList();

	}

	@SuppressWarnings("unchecked")
	public List<Actor> selectActorByAge(Integer age) {


		Calendar datInit = Calendar.getInstance();
		datInit.add(Calendar.YEAR, -(age + 1));
		
		Calendar datEnd = Calendar.getInstance();
		datEnd.add(Calendar.YEAR, -age);

		
		System.err.println("datInit: " + datInit.get(Calendar.DAY_OF_MONTH) +  datInit.get(Calendar.MONTH) + datInit.get(Calendar.YEAR));
		System.err.println("datEnd: " + datEnd.get(Calendar.DAY_OF_MONTH) +  datEnd.get(Calendar.MONTH) + datEnd.get(Calendar.YEAR));
		
		Query query = em
				.createQuery(" SELECT a FROM Actor a where a.birthDate BETWEEN :datInit AND :datEnd");

		query.setParameter("datInit", datInit.getTime());
		query.setParameter("datEnd", datEnd.getTime());
		
		
		return query.getResultList();
		
	}

	@SuppressWarnings("unchecked")
	public List<Actor> selectActorsByMovie(Movie movie) {
	
		System.err.println("MovieId: " + movie.getId());
		
		Query query = em.createQuery("SELECT a from Actor a " +
		" inner join a.movies m " +
		" where m.id = :movieId ");
		
		query.setParameter("movieId", movie.getId());
		
		return query.getResultList();
		
	}

	@SuppressWarnings("unchecked")
	public List<Actor> selectActors(int numberOfElements) {
		
		Query query = em
				.createQuery(" SELECT a FROM Actor a");

		query.setMaxResults(numberOfElements);
		
		return query.getResultList();
		
	}
	
	@SuppressWarnings("unchecked")
	public List<Actor> selectActorsWithMovie(int numberOfElements) {
	
		Query query = em.createQuery("SELECT a from Actor a " +
		" inner join a.movies m ");
		
		query.setMaxResults(numberOfElements);
		
		return query.getResultList();
		
	}
}
